/**
 * 电子围栏-页面使用
 */

var overlays = [];
var linelnglatArr = [];

var plls = [];

// 百度地图API功能
var map = new BMap.Map("map-dg", {
	enableMapClick : false
});
var poi = new BMap.Point(116.307852, 40.057031);
//map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);
map.centerAndZoom(poi, 14);
// map.enableScrollWheelZoom();
map.enableScrollWheelZoom(true);

/**
 * 清空所有电子围栏设置
 * @returns
 */
function clearAll() {
	console.log(overlays.length);
	for (var i = 0; i < overlays.length; i++) {
		map.removeOverlay(overlays[i]);
	}
	overlays.length = 0;
}

/**
 * 恢复所有电子围栏设置
 * @returns
 */
function recoveryAll() {
	/*
	 * for(var i = 0; i < overlays.length; i++){ map.addOverlay(overlays[i]);
	 * console.log(overlays[i]); console.log(JSON.stringify(overlays[i])); }
	 */
	console.log("恢复长度：" + plls);
	for (var i = 0; i < plls.length; i++) {
		console.log("恢复index：" + i + "内容：" + plls[i]);
		console.log(plls[0] === plls[1]);
		var pointArr = plls[i];
		//console.log(pointArr.lng);
		//console.log(pointArr.lat);
		var polygon = new BMap.Polygon(pointArr, {
			strokeColor : "blue",
			strokeWeight : 3,
			strokeOpacity : 0.5
		});
		map.addOverlay(polygon);
		overlays.push(polygon);
	}

}

var fenceInfoUrl = "electronicFence/busFenceInfo.do";
var b;

//var listUrl = "map/mapList.do"; // 列表展示url
$(document).ready(function() {
	
	
	//createMap()
	//loanMap();
	setTimeout(loanMap,"1000");
	$('#fence-fm').form('syncLoad', fenceInfoUrl + "?carNo=" + carNo);
    //plls = $('#drawing').val();
	var drawing = $('#drawing').val();
	if(drawing.length > 0) {
		var b = eval(drawing);
		if(b.length > 0) {
	    	plls = b;
	        console.log(b.length);
	        setTimeout(recoveryAll,"2000");//recoveryAll();
	    }
	}
})

/*function createMap(param) {
	$.ajax({
		url : listUrl,
		type : "post",
		data : param,
		success : function(data) {
			loanMap(data);
		}
	});
}*/

/**
 * 加载地图
 * @returns
 */
function loanMap() {

	var overlaycomplete = function(e) {
		overlays.push(e.overlay);
		var result = "";
		result = "<p>";
		result += e.drawingMode + ":";
		if (e.drawingMode == BMAP_DRAWING_MARKER) {
			result += '坐标:' + e.overlay.getPosition().lng + ','
					+ e.overlay.getPosition().lat;
			if ($('isInfowindow').checked) {
				searchInfoWindow.open(e.overlay);
			}
		}
		if (e.drawingMode == BMAP_DRAWING_CIRCLE) {
			result += '半径：' + e.overlay.getRadius();
			result += '中心点：' + e.overlay.getCenter().lng + ','
					+ e.overlay.getCenter().lat;
		}
		if (e.drawingMode == BMAP_DRAWING_POLYLINE
				|| e.drawingMode == BMAP_DRAWING_POLYGON
				|| e.drawingMode == BMAP_DRAWING_RECTANGLE) {
			result += '所画的点个数：' + e.overlay.getPath().length;
			// e.overlays_lines.length; e.overlays_lines[i].getPath().length;
			var pll = [];
			for (var i = 0; i < e.overlay.getPath().length; i++) {
				var object = new Object();
				object.lnglatX = e.overlay.getPath()[i].lng;
				object.lnglatY = e.overlay.getPath()[i].lat;
				linelnglatArr.push(object);

				result += '坐标:' + e.overlay.getPath()[i].lng + ','
						+ e.overlay.getPath()[i].lat;
				pll[i] = new BMap.Point(e.overlay.getPath()[i].lng, e.overlay
						.getPath()[i].lat);
				
			}
			
			var pllsLength = plls.length;
			console.log("当前二维数组长度：" + pllsLength);
			plls[pllsLength] = pll;
		}
		result += "</p>";
		//console.log(result);
		//console.log(JSON.stringify(plls));
		$("#drawing").val(JSON.stringify(plls));
	};

	var styleOptions = {
		strokeColor : "red", // 边线颜色。
		fillColor : "red", // 填充颜色。当参数为空时，圆形将没有填充效果。
		strokeWeight : 3, // 边线的宽度，以像素为单位。
		strokeOpacity : 0.8, // 边线透明度，取值范围0 - 1。
		fillOpacity : 0.6, // 填充的透明度，取值范围0 - 1。
		strokeStyle : 'solid' // 边线的样式，solid或dashed。
	}
	// 实例化鼠标绘制工具
	/*var drawingManager = new BMapLib.DrawingManager(map, {
		isOpen : false, // 是否开启绘制模式
		enableDrawingTool : true, // 是否显示工具栏
		drawingToolOptions : {
			anchor : BMAP_ANCHOR_TOP_RIGHT, // 位置
			offset : new BMap.Size(5, 5), // 偏离值
		},
		circleOptions : styleOptions, // 圆的样式
		polylineOptions : styleOptions, // 线的样式
		polygonOptions : styleOptions, // 多边形的样式
		rectangleOptions : styleOptions // 矩形的样式
	});*/
	// 添加鼠标绘制工具监听事件，用于获取绘制结果
	//drawingManager.addEventListener('overlaycomplete', overlaycomplete);
	
	 var drawingManager = new BMapLib.DrawingManager(map, {
	        isOpen: false, //是否开启绘制模式
	        enableDrawingTool: true, //是否显示工具栏
	        drawingToolOptions: {
	            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
	            offset: new BMap.Size(5, 5), //偏离值
	        },
	        circleOptions: styleOptions, //圆的样式
	        polylineOptions: styleOptions, //线的样式
	        polygonOptions: styleOptions, //多边形的样式
	        rectangleOptions: styleOptions //矩形的样式
	    });  
		 //添加鼠标绘制工具监听事件，用于获取绘制结果
	    drawingManager.addEventListener('overlaycomplete', overlaycomplete);
}

$("#submit-search").click(function() {
	createMap(form2Json("fmsFence")); // 点击搜索
});


/**
 * 保存电子围栏
 * @returns
 */
function saveFence() {
	$('#fence-fm').form('submit', {
		url : 'electronicFence/uploadBusFence.do', 
		onSubmit : function() {
			var validator = $(this).form('validate');
			if (validator) {
				$.messager.progress();
			}
			return validator;
		},
		success : function(result) {
			$.messager.progress('close');
			result = eval('(' + result + ')');
			if (result.success == 'true') {
				back('electronicFence/index.do');
				
			} else {
				$.messager.show({
					title : 'Error',
					msg : result.msg
				});
			}
		}
	});
}

function back(url){
	$.get(url, {}, function(data){
		$("#center").empty();
        $("#center").html(data);
        $.parser.parse($("#center"));
    });
}